/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF SCRUM DASHBOARD.

SCRUM DASHBOARD IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUM DASHBOARD IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUM DASHBOARD. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using ScrumDashboard.Library;
using ScrumDashboard.Library.Model;
using ScrumDashboard.Library.Tfs;

namespace ScrumDashboard.ui
{
    public partial class ImportBugsView : System.Web.UI.UserControl
    {
        TfsManager _tfs;

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterStartupScript(typeof(CreateTaskView), "importBugsPopupBehaviorClientID", "var importBugsPopupBehaviorClientID = '" + importBugsPopupBehavior.ClientID + "';", true);

            if (!IsPostBack)
            {
                projectList.Items.Clear();
                projectList.Items.Add(new ListItem("<Select project>", ""));
                foreach (Project proj in TFS.GetProjectsWithWIT())
                {
                    projectList.Items.Add(new ListItem(proj.Name, proj.Name));
                }
            }
        }

        private TfsManager TFS
        {
            get
            {
                if (_tfs == null)
                    _tfs = new TfsManager();
                return _tfs;
            }
        }

        protected void ReloadQueries(object sender, EventArgs e)
        {
            queryList.Visible = true;
            queryList.Items.Clear();
            queryList.Items.Add(new ListItem("<Select query>", ""));
            if (projectList.SelectedValue.Length > 0)
            {
                StoredQueryCollection queries = TFS.GetQueries(projectList.SelectedValue);
                foreach (StoredQuery q in queries)
                {
                    queryList.Items.Add(new ListItem(q.Name, q.QueryGuid.ToString()));
                }

                DataBind();
            }
        }

        protected void ReloadBugs(object sender, EventArgs e)
        {
            if (projectList.SelectedValue.Length > 0)
            {
                bugList.DataSource = TFS.ExecuteQuery(projectList.SelectedValue,new Guid(queryList.SelectedValue));
                DataBind();
            }
        }

        protected string SelectableWorkItem(object o)
        {
            WorkItem wi = (WorkItem)o;
            if (wi.RelatedLinkCount > 0)
            {
                foreach (Link y in wi.Links)
                {
                    if (y.Comment == "Scrum2BugLink")
                    {
                        WorkItem scrum = TFS.GetWorkItem(((RelatedLink)y).RelatedWorkItemId);
                        if (scrum.State == "Deleted")
                            continue;

                        //Make sure we don't disable bugs related to old sprints
                        SprintItem sprint = TFS.GetSprint(scrum.IterationId);
                        if (sprint == null)
                            continue;
                        if (sprint.SprintEnd < DateTime.Now)
                            continue;

                        return "name=\"DisabledWorkItemTemp\" checked=\"checked\" disabled=\"disabled\" title=\"Already linked to sprint " + scrum.IterationPath + ", see bug links for details\"";
                    }
                }
            }

            return "name=\"workItemID\"";
        }

        protected string GetField(object o, string field)
        {
            WorkItem wi = (WorkItem)o;
            if (!wi.Fields.Contains(field))
                return String.Empty;
            else if (wi.Fields[field].Value == null)
                return string.Empty;
            else
                return wi.Fields[field].Value.ToString();
        }

        protected void AddSelected(object sender, EventArgs e)
        {
            int backLogId = Int32.Parse(Request.Form["SelectedProductBacklogID"]);
            string workItemIds = Request.Form["workItemID"];
            if (!String.IsNullOrEmpty(workItemIds))
            {

                string[] workItemArray = workItemIds.Split(',');
                foreach (string workItem in workItemArray)
                {
                    int id = Int32.Parse(workItem);
                    TFS.CreateScrumBug(((_Default)Page).CurrentSprint,backLogId, id);

                }
                saveMessage.Text = "Imported " + workItemArray.Length.ToString() + " bugs";
            }

            ReloadBugs(this, EventArgs.Empty);
            ImportBugsViewUP.Update();
            ((_Default)Page).Update();
        }
    }
}